﻿# -*- coding:utf-8 -*-
import datetime
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext, Context
from django.core.urlresolvers import reverse

from ktit.storage.forms import CategoryForm, PartForm, DocumentForm, DocumentReceiptForm, DocumentDeliveryForm 
from ktit.storage.models import Category, Part, PartItem, Document, DocumentItem, DocumentReceipt, DocumentDelivery, Unit, Place
from ktit.storage.categories import create_cat_tree
#from ktit.storage.historypath import *

from ktit.storage.contextprocessors import category_proc




@login_required
#def editpart(request, partid):
def edit(request, partid):
    #history_path_add(request, HP_EDIT_PART)
    part_inst = Part.objects.get(id=partid)
    if request.method == 'POST':
        form = PartForm(request.POST, instance=part_inst)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('ktit.storage.views.categorys.view', args=[(request.session["current_category"])])) 
    else:
        form = PartForm(instance=part_inst)
    return render_to_response('form_part_edit.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))


@login_required
def create(request):
#def addpart(request):
    #history_path_add(request, HP_NEW_PART)
    if request.method == 'POST':
        form = PartForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('ktit.storage.views.categorys.view', args=[(request.session["current_category"])]))
    else:
        form = PartForm(initial={'category': request.session["current_category"]})
    return render_to_response('form_part_add.html', {'form' : form}, context_instance=RequestContext(request, processors=[category_proc]))


@login_required
def delete(request, item):
#def deletepart(request, item):
    pass
    
    
    
@login_required    
def property(request, part_id):    
#def partinfo(request, part_id): 
    part = get_object_or_404(Part, id = part_id)
    category = part.category
    receipts = DocumentItem.objects.select_related().filter(part=part_id, document__kind='R')
    deliverys= DocumentItem.objects.select_related().filter(part=part_id, document__kind='D')
    #receipts = Document.objects.select_related().filter(documentitem__part=part_id, kind='R')
    count = 'n/a'
    #if part.numbered == 'N':
        #count = int(RegPart.objects.filter(part=part).aggregate(Sum('quantity'))['quantity__sum'])
    #    count = RegPart.partcount.part_quantity(part_id)['part_quantity']
    #    print count
    #else:
    #    count = RegNumberedPart.objects.filter(part=part, out_doc=None).count()   
   
    context = Context({
      'category' : category,
      'part' : part,
      'receipts':receipts,
      'deliverys':deliverys,
      'count':count,
    })
    return render_to_response('part_property.html', context, context_instance=RequestContext(request, processors=[category_proc]))


@login_required    
def serials(request, part_id):    
    part = get_object_or_404(Part, id = part_id)
    category = part.category
    serials = PartItem.objects.select_related().filter(part=part_id, document_state='R')  
    
    if request.method == 'POST':
        if request.POST.has_key('save_serials'): 
            print "button _save_serials_ pressed..."  
            if request.POST.has_key('serials'):
                change_serials = [v for v in request.POST.getlist('serials') if v != '']
                print change_serials

        if request.POST.has_key('delivery_serials'): 
            print "button _delivery_serials_ pressed..."  
            if request.POST.has_key('selected_serial'):
                selected_serial = [v for v in request.POST.getlist('selected_serial') if v != '']
                print selected_serial
           
    context = Context({
      'category' : category,
      'part' : part,
      'serials':serials,  
    })
    return render_to_response('part_serial.html', context, context_instance=RequestContext(request, processors=[category_proc]))

    